package com.zheng.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2018/4/19
 * Time: 11:54
 */
public class Pagination implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer offset;
    private Integer limit;
    private Integer pageNumber;
    private Integer pageSize;
    private String sortOrder;
    private String sortName;
    private final Integer DEFAULT_PAGE_SIZE = 10;

    //    private int current;
    //    private int total;
    public Pagination(Integer pageNumber, Integer pageSize, String sortOrder, String sortName) {
        if (StringUtils.isNotBlank(sortOrder)) {
            this.sortOrder = sortOrder;
        }
        if (StringUtils.isNotBlank(sortName)) {
            this.sortName = sortName;
        }
        if (pageNumber != null && pageSize != null) {
            this.pageNumber = pageNumber;
            this.pageSize = pageSize;
            this.offset = offsetCurrent(this.pageNumber, this.pageSize);
            this.limit = this.pageSize;
        }
    }

    //计算offset
    protected static int offsetCurrent(int pageNumber, int pageSize) {
        if (pageNumber > 0) {
            return (pageNumber - 1) * pageSize;
        }
        return 0;
    }

    protected static int pageNumberCurrent(int offset, int limit) {
        return (offset / limit) + 1;
    }

    public Integer getOffset() {
        return offset;
    }

    public void setOffset(Integer offset) {
        this.offset = offset;
        this.pageNumber = pageNumberCurrent(offset, this.limit);
    }

    public Integer getLimit() {
        return limit;
    }

    public void setLimit(Integer limit) {
        this.limit = limit;
    }

    public Integer getPageNumber() {
        return pageNumber;
    }

    public void setPageNumber(Integer pageNumber) {
        this.pageNumber = pageNumber;
        this.offset = offsetCurrent(pageNumber, this.pageSize);
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public String getSortOrder() {
        return sortOrder;
    }

    public void setSortOrder(String sortOrder) {
        this.sortOrder = sortOrder;
    }

    public String getSortName() {
        return sortName;
    }

    public void setSortName(String sortName) {
        this.sortName = sortName;
    }
}
